from PyQt6.QtWidgets import QWidget, QVBoxLayout
from PyQt6.QtWebEngineWidgets import QWebEngineView


class EChartsWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.setMinimumHeight(500)
        self.setup_chart()

        # 数据存储
        self.max_points = 120
        self.cpu_data = []
        self.memory_data = []
        self.disk_data = []
        self.swap_data = []
        self.time_labels = []

    def setup_chart(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)

        # 创建WebEngine视图来显示ECharts
        self.web_view = QWebEngineView()
        self.web_view.setMinimumHeight(430)
        layout.addWidget(self.web_view)

        # 初始化图表
        self.init_chart()

    def init_chart(self):
        html_content = """
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
</head>
<body>
    <div id="chart" style="width: 100%; height: 480px;"></div>
    <script>
        var chart = echarts.init(document.getElementById('chart'), null, {
            renderer: 'canvas'
        });

        var option = {
            title: {
                text: '系统资源实时监控',
                left: 'center',
                top: 10,
                textStyle: {
                    color: '#2c3e50',
                    fontSize: 18,
                    fontWeight: '600'
                }
            },
            backgroundColor: '#fafafa',
            tooltip: {
                trigger: 'axis',
                backgroundColor: 'rgba(50, 50, 50, 0.9)',
                borderColor: 'transparent',
                textStyle: { color: '#fff', fontSize: 12 },
                axisPointer: {
                    type: 'cross',
                    crossStyle: { color: '#999' }
                },
                formatter: function(params) {
                    let result = '<div style="font-weight:bold;margin-bottom:5px;">' + params[0].name + '</div>';
                    params.forEach(function(item) {
                        result += `<div style="margin:2px 0;">
                            <span style="color:${item.color};">●</span> 
                            ${item.seriesName}: <strong>${item.value.toFixed(1)}%</strong>
                        </div>`;
                    });
                    return result;
                }
            },
            legend: {
                data: ['CPU', '内存', '系统盘', '交换内存'],
                top: 35,
                itemGap: 20,
                textStyle: { color: '#34495e', fontSize: 13 }
            },
            grid: {
                left: '3%', right: '3%', bottom: '8%', top: '18%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: [],
                axisLine: { lineStyle: { color: '#ddd' } },
                axisLabel: { color: '#666', fontSize: 11 },
                splitLine: { 
                    show: true,
                    lineStyle: { color: '#f0f0f0', type: 'dashed', width: 1 }
                }
            },
            yAxis: {
                type: 'value',
                min: 0, max: 100,
                axisLine: { lineStyle: { color: '#ddd' } },
                axisLabel: { 
                    color: '#666', 
                    fontSize: 11,
                    formatter: '{value}%'
                },
                splitLine: { 
                    lineStyle: { color: '#f0f0f0', type: 'dashed', width: 1 }
                }
            },
            series: [
                {
                    name: 'CPU',
                    type: 'line',
                    data: [],
                    smooth: 0.3,
                    symbol: 'none',
                    lineStyle: { color: '#3498db', width: 2 },
                    areaStyle: {
                        color: {
                            type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
                            colorStops: [
                                { offset: 0, color: 'rgba(52, 152, 219, 0.4)' },
                                { offset: 1, color: 'rgba(52, 152, 219, 0.05)' }
                            ]
                        }
                    }
                },
                {
                    name: '内存',
                    type: 'line',
                    data: [],
                    smooth: 0.3,
                    symbol: 'none',
                    lineStyle: { color: '#27ae60', width: 2 },
                    areaStyle: {
                        color: {
                            type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
                            colorStops: [
                                { offset: 0, color: 'rgba(39, 174, 96, 0.4)' },
                                { offset: 1, color: 'rgba(39, 174, 96, 0.05)' }
                            ]
                        }
                    }
                },
                {
                    name: '系统盘',
                    type: 'line',
                    data: [],
                    smooth: 0.3,
                    symbol: 'none',
                    lineStyle: { color: '#f39c12', width: 2 },
                    areaStyle: {
                        color: {
                            type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
                            colorStops: [
                                { offset: 0, color: 'rgba(243, 156, 18, 0.4)' },
                                { offset: 1, color: 'rgba(243, 156, 18, 0.05)' }
                            ]
                        }
                    }
                },
                {
                    name: '交换内存',
                    type: 'line',
                    data: [],
                    smooth: 0.3,
                    symbol: 'none',
                    lineStyle: { color: '#FF5722', width: 2 },
                    areaStyle: {
                        color: {
                            type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
                            colorStops: [
                                { offset: 0, color: 'rgba(255, 87, 34, 0.4)' },
                                { offset: 1, color: 'rgba(255, 87, 34, 0.05)' }
                            ]
                        }
                    }
                }
            ],
            animation: false
        };

        chart.setOption(option);

        // 自适应窗口大小
        window.addEventListener('resize', () => chart.resize());

        // 数据更新函数
        window.updateChartData = function(cpu, memory, disk, swap) {
            const now = new Date();
            const timeStr = now.toLocaleTimeString('zh-CN', { hour12: false });

            const option = chart.getOption();

            // 添加新数据点
            option.xAxis[0].data.push(timeStr);
            option.series[0].data.push(cpu);
            option.series[1].data.push(memory);
            option.series[2].data.push(disk);
            option.series[3].data.push(swap);

            // 保持数据点数量限制
            if (option.xAxis[0].data.length > 120) {
                option.xAxis[0].data.shift();
                option.series[0].data.shift();
                option.series[1].data.shift();
                option.series[2].data.shift();
                option.series[3].data.shift();
            }

            chart.setOption(option);
        };
    </script>
</body>
</html>
        """

        self.web_view.setHtml(html_content)

    def update_data(self, cpu_val, memory_val, disk_val, swap_val):
        # 通过JavaScript更新图表数据
        script = f"if(window.updateChartData) window.updateChartData({cpu_val}, {memory_val}, {disk_val}, {swap_val});"
        self.web_view.page().runJavaScript(script)

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self.web_view.page().runJavaScript("if(window.chart) window.chart.resize();")